package com.voxel.sense.infomsg.module.map.warn;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.L;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.activity.SendUrgencyTaskActivity;
import com.voxel.sense.infomsg.data.bean.MakerInfoBean;
import com.voxel.sense.infomsg.module.firm.details.FirmInfoDetailActivity;
import com.voxel.sense.infomsg.module.publish.PublishFileActivity;
import com.voxel.sense.infomsg.module.task.send.SendTaskActivity;
import com.voxel.sense.infomsg.module.task.send.SendTaskContract;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.FacilityAbnorDataConvertStrategy;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.WOutLBeanConvertStrategy;
import com.voxel.sense.infomsg.view.MenuBean;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.map.MapInfoPopWindows;
import com.voxel.sense.infomsg.widget.map.adpter.MarkerInfoWinowAdapter;
import com.voxel.sense.infomsg.widget.map.utils.IMarkerManage;
import com.voxel.sense.infomsg.widget.map.utils.MarkerManageUtils;
import com.voxel.sense.infomsg.widget.map.utils.OnCtmMarkerClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.FirmLatestOverDataEntity;
import cyy.example.com.facotry.model.api.response.FirmLocationEntity;
import cyy.example.com.facotry.model.api.response.WarningFirmEntity;

/**
 * Created by chenyiyao on 2017/11/1.
 * 超标预警模块
 */

public class FirmWarnActivity extends BViewActivity<FirmWarnContract.Presenter> implements
  AMap.OnMyLocationChangeListener, AMap.OnMapClickListener, FirmWarnContract.View<MakerInfoBean> {

  @BindView(R.id.map_view)
  MapView map_view;
  @BindView(R.id.titlebar)
  TextTitleBar titlebar;
  @BindView(R.id.iv_data_over)
  ImageView iv_data_over;
  @BindView(R.id.iv_facility)
  ImageView iv_facility;
  @BindView(R.id.tv_data_over_tip)
  TextView tv_data_over_tip;
  @BindView(R.id.tv_facility_tip)
  TextView tv_facility_tip;
  @BindView(R.id.recycle_view)
  RecyclerView mRecyclerView;

  private AMap aMap;//地图操控类
  Marker mCurrentClickMarker;
  private MarkerInfoWinowAdapter mMapInfoWindowAdapter;//地图marker信息窗口的适配器
  //    private MapMarkerManager mMarkerManager;//marker管理器
  private MyLocationStyle myLocationStyle;//map定位的样式

  private boolean isMoveMyLocation = true;//以此数据来判断是否移动到我的位置
  private double mLatitude; //初始化地图中心点的纬度
  private double mLongitude; //初始化地图中心点的经度
  private IMarkerManage mMarkerManager;//marker管理器
  private MapInfoPopWindows mWindows; //底部信息窗口
  private FirmWarnAdapter firmWarnAdapter;
  private MakerInfoBean body;

  public static void show(Context context, FirmLocationEntity entity, double latitude, double longitude) {
    Intent intent = new Intent(context, FirmWarnActivity.class);
    Bundle bundle = new Bundle();
    if (entity != null) {
      bundle.putSerializable(IntentConstants.OBJECT_TYPE, entity);
    }
    bundle.putDouble(IntentConstants.LATITUDE, latitude);
    bundle.putDouble(IntentConstants.LONGITUDE, longitude);
    intent.putExtras(bundle);
    context.startActivity(intent);
  }

  @Override
  protected int getContentLayoutId() {
    return R.layout.activity_map_warn;
  }

  @Override
  protected FirmWarnContract.Presenter initPresenter() {
    return new FirmWarnPresenter(this);
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    map_view.onCreate(savedInstanceState);
  }

  /**
   * 方法必须重写
   */
  @Override
  protected void onResume() {
    super.onResume();
    map_view.onResume();
  }

  /**
   * 方法必须重写
   */
  @Override
  protected void onPause() {
    super.onPause();
    map_view.onPause();
  }

  /**
   * 方法必须重写
   */
  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    map_view.onSaveInstanceState(outState);
  }

  /**
   * 方法必须重写
   */
  @Override
  protected void onDestroy() {
    super.onDestroy();
    map_view.onDestroy();
    mMarkerManager.onDestory();
  }

  @Override
  protected boolean initArgs(Bundle bundle) {
    if (bundle != null) {
      mLatitude = bundle.getDouble(IntentConstants.LATITUDE, 0);
      mLongitude = bundle.getDouble(IntentConstants.LONGITUDE, 0);
    }
    return super.initArgs(bundle);
  }

  @Override
  protected void initData() {
    super.initData();
    if (aMap == null) {
      aMap = map_view.getMap();
//      if (mLatitude != -1 && mLongitude != -1) {
        //移动地图中心点
        aMap.moveCamera(CameraUpdateFactory.
          changeLatLng(new LatLng(23.653317, 114.665524)));
      aMap.moveCamera(CameraUpdateFactory. zoomTo(13));
//      }
    }
    iv_data_over.setSelected(false);
    iv_facility.setSelected(true);
    //添加入marker管理容器中
    mMarkerManager = new MarkerManageUtils(aMap);
    titlebar.setTitleText("异常警告");
    //初始化地图
    initMap();
    initRv(null);

    //加载超标公司的信息
    mPresenter.doLoadWarningFirm();
  }

  @Override
  protected void initEven() {
    super.initEven();
    if(mWindows != null) {
      mWindows.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
          L.d("--setOnDismissListener---消失监听");
        }
      });

    }
    mMarkerManager.setMarkerClickListener(new OnCtmMarkerClickListener() {
      @Override
      public boolean onNoClusterClick(Marker marker, Object o) {
        if (!NetworkUtils.isConnected()) {
          ToastUtil.showToastLong(Factory.app(), getString(R.string.network_unavailable));
          return true;
        }
//                mWindows.show();
        handleMakerClickEvnet(marker);
        return true;
      }

      @Override
      public boolean onClusterClick(Marker marker) {
        hideMarkInfoWindow();
        return true;
      }
    });
  }

  @OnClick({R.id.iv_data_over, R.id.iv_facility})
  void onClickEvent(View view) {
    boolean selected = !view.isSelected();
    if (view.getId() == R.id.iv_data_over) {
      //改变状态
      iv_data_over.setSelected(selected);
      mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_WARN_OVER_FIRM, selected, true);
      if (selected) {
        iv_facility.setSelected(false);
        mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_WARN_FACILITY_FIRM, false, false);

        //显示提示窗口
        tv_data_over_tip.setVisibility(View.VISIBLE);
        tipGoneAnimation(tv_data_over_tip);
      }
    }
    else if (view.getId() == R.id.iv_facility) {
      iv_facility.setSelected(selected);
      mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_WARN_FACILITY_FIRM, selected, selected);
      if (selected) {
        iv_data_over.setSelected(false);
        mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_WARN_OVER_FIRM, false, false);
        //显示提示窗口
        tv_facility_tip.setVisibility(View.VISIBLE);
        tipGoneAnimation(tv_facility_tip);
      }
    }
  }
//
//
//    @Override
//    public void onUpStaffMarker(List datas) {
////        mMarkerManager.addMarker(datas, Constants.MARKER_TYPE_PEOPLE);
//        Drawable drawable = getResources().getDrawable(R.mipmap.marker_people_icon);
//        StaffConverStrategey strategey = new StaffConverStrategey();
//        String type = Constants.MARKER_TYPE_PEOPLE;
//        if (mIsRefreshStaff) {
//            mMarkerManager.refreshMarkers(datas, type, strategey);
//        } else {
//            mIsRefreshStaff = true;
//            mMarkerManager.addMarkers(datas, type, drawable, strategey);
//        }
//    }

  @Override
  public void onUpOverLimitDataMarker(List datas) {
    Drawable drawable = getResources().getDrawable(R.mipmap.ic_over_tip);
    WOutLBeanConvertStrategy strategey = new WOutLBeanConvertStrategy();
    mMarkerManager.addMarkers(datas, Constants.MARKER_TYPE_WARN_OVER_FIRM, drawable, strategey);

      for (int i = 0; i < datas.size(); i++) {
        WarningFirmEntity.OutOfLimitCompanyBean data = (WarningFirmEntity.OutOfLimitCompanyBean) datas.get(i);
        mPresenter.getComputeInfoById(data.getCompanyId(), Constants.TYPE_WARM_DEVICE);
      }


    //是否需要定位到第一个
//        WarningFirmEntity.OutOfLimitCompanyBean bean = (WarningFirmEntity.OutOfLimitCompanyBean) datas.get(0);
//        aMap.moveCamera(CameraUpdateFactory.
//                        changeLatLng(new LatLng(Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()))));
  }

  private void initRv(List datas) {
    //初始化recyclerView
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(layoutManager);
    firmWarnAdapter = new FirmWarnAdapter();
    mRecyclerView.setAdapter(firmWarnAdapter);
    firmWarnAdapter.setOnItemClickener(new FirmWarnAdapter.OnItemClickListeners() {
      @Override
      public void onClick(FirmLatestOverDataEntity data, int position) {
//                PublishFileActivity.show(FirmWarnActivity.this);
//        Log.e("+++","sdfdsf"+data.getSiteData().get(position).getWatchsiteName());

        String watchSitName = "";
        if(data.getSiteData() != null && data.getSiteData().size() > 0 &&data.getSiteData().get(0) != null){
          if(!TextUtils.isEmpty(data.getSiteData().get(0).getWatchsiteName())){
            watchSitName = data.getSiteData().get(0).getWatchsiteName();
          }else{
            watchSitName = "";
          }
        }else{
          watchSitName = "";
        }
        SendTaskActivity.show(FirmWarnActivity.this, SendTaskContract.WARM_TASK, data, watchSitName);
      }
    });
    firmWarnAdapter.setOnComClickener(new FirmWarnAdapter.OnComponeClickener() {
      @Override
      public void onComClick(FirmLatestOverDataEntity data) {
        aMap.moveCamera(CameraUpdateFactory.
                        changeLatLng(new LatLng(Double.parseDouble(data.getLatitude()), Double.parseDouble(data.getLongitude()))));
        mPresenter.getItemClickInfo(data.getCompanyId());
      }

    });
  }

  @Override
  public void onUpFacilityAbnorDataMarker(List datas) {
    Drawable drawable = getResources().getDrawable(R.mipmap.ic_marker_firm);
    FacilityAbnorDataConvertStrategy strategey = new FacilityAbnorDataConvertStrategy();
//        strategey.setVisible(false);


      for (int i = 0; i < datas.size(); i++) {
        WarningFirmEntity.UnusualCompanyBean data = (WarningFirmEntity.UnusualCompanyBean) datas.get(i);
        mPresenter.getComputeInfoById(data.getCompanyId(), Constants.TYPE_WARM_OVER);
      }


    mMarkerManager.addMarkers(datas, Constants.MARKER_TYPE_WARN_FACILITY_FIRM, drawable, strategey);

  }

  @Override
  public void noData(int type) {
      mRecyclerView.setVisibility(View.GONE);
  }

  @Override
  public void onShowInfoWindows(MakerInfoBean body) {

    showInfoWindowData(body);
  }

  @Override
  public void onShowWindows(MakerInfoBean body) {
    showInfoWindowData(body);
  }

  List<FirmLatestOverDataEntity> data = new ArrayList<>();

  @Override
  public void onShowInfo(FirmLatestOverDataEntity body, int type) {
    if(type == Constants.TYPE_WARM_OVER) {
      body.setOverData(1);
      data.add(body);
    }else if(type == Constants.TYPE_WARM_DEVICE){
      body.setOverData(2);
      data.add(body);
    }

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if(data.size() <= 0){
          mRecyclerView.setVisibility(View.GONE);
        }else{
          mRecyclerView.setVisibility(View.VISIBLE);
        }
//        if(type == Constants.TYPE_WARM_OVER) {
          firmWarnAdapter.setData(data);
//        }else{
//          firmWarnAdapter.setData(data1);
//        }
//                initRv(datas);
      }
    });
  }

  @Override
  public void onLoadMakIconFinish(Map<String, Drawable> map) {
    if (map != null)
      mMarkerManager.putDrawables(map);
  }

  /**
   * 初始化地图
   */
  private void initMap() {
    setLocationStyle();//设置定位样式
    initMarkerInfoWindow();//初始化MrkerInfo窗口
    //地图自身的定位按钮定位的回调
    aMap.setOnMyLocationChangeListener(this);

    aMap.setOnMapClickListener(this);

    //点击地图上的markerInfo窗口点击事件，绑定信息窗点击事件
    aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
      @Override
      public void onInfoWindowClick(Marker marker) {
        //todo:

      }
    });
  }

  /**
   * 人员类型菜单事件处理
   */
  private void handleMenuEvent(int position, MenuBean bean) {
    if (mMarkerManager == null)
      return;
    if (position == 0) {
      //选中全部选项
      mMarkerManager.setSomeTypeMarkersVisible(Constants.MARKER_TYPE_PEOPLE, bean.isSelect(), false);
    }
    else {
      mMarkerManager.setSameIdMarkersVisible(Constants.MARKER_TYPE_PEOPLE, bean.getID(), bean.isSelect());
//            for (Marker data : markers) {
//                PeopleMarkerEntity.BodyBean object = (PeopleMarkerEntity.BodyBean) data.getObject();
//                //选择不同类型，隐藏不同的数据
//                String type = object.getPersonRoleId();
//                if (!TextUtils.isEmpty(type) && type.equals(bean.getID())) {
//                    data.setVisible(bean.isSelect());
//                }
//            }
    }
  }

  private void initMarkerInfoWindow() {
    //初始化markerInfo窗口的样式
    mMapInfoWindowAdapter = new MarkerInfoWinowAdapter(this);
    mMapInfoWindowAdapter.setFirmTypeSenTask(true);
//        //info窗口子view的点击事件
    mMapInfoWindowAdapter.setOnFirmWindowClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {

        if (mCurrentClickMarker == null)
          return;
        PublishFileActivity.show(FirmWarnActivity.this);
        switch (view.getId()) {
          case R.id.tv_firm_detail://公司详情
            String firmId = mMapInfoWindowAdapter.getCurrentMarkerID(Constants.MARKER_TYPE_FIRM);
            FirmInfoDetailActivity.show(FirmWarnActivity.this, null, firmId);
            break;
          case R.id.tv_mission://派发任务
            String taskId = mMapInfoWindowAdapter.getCurrentMarkerID(Constants.MARKER_TYPE_PEOPLE);
            ToastUtil.showToastLong(FirmWarnActivity.this, "创建任务" + taskId);
            SendUrgencyTaskActivity.show(FirmWarnActivity.this, taskId);
            break;
        }
      }
    });

    //这里先注释了地图上的点弹出
    aMap.setInfoWindowAdapter(mMapInfoWindowAdapter);

    //自定义的底部弹窗


  }

  /**
   * 设置地图定位相关设置
   */
  private void setLocationStyle() {
    //获取map的ui设置类
    UiSettings settings = aMap.getUiSettings();
    // 设置显示定位按钮 并且可以点击
    settings.setMyLocationButtonEnabled(true);
    // 是否可触发定位并显示定位层
    aMap.setMyLocationEnabled(false);
    //定位的小图标 默认是蓝点 这里自定义一团火，其实就是一张图片
    myLocationStyle = new MyLocationStyle();
    //连续定位、蓝点不会移动到地图中心点，并且蓝点会跟随设备移动。
    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
    myLocationStyle.radiusFillColor(android.R.color.transparent);
    myLocationStyle.strokeColor(android.R.color.transparent);
    aMap.setMyLocationStyle(myLocationStyle);
  }

  /**
   * 地图marker点击事件处理方法
   */
  private void handleMakerClickEvnet(Marker marker) {
    String title = marker.getTitle();
    mCurrentClickMarker = marker;
    //记录当前点击的marker,从网络加载完数据后，根据id对比，是否同一个marker的窗口，再进行初始化窗口数据
    mMapInfoWindowAdapter.setCurrentClickMarker(marker);//记录到适配器中
    mMapInfoWindowAdapter.setLoadDataComplete(false);
    //加载marker的信息窗口
    mPresenter.doLoadMarkerInfo(marker, title);

    LatLng position = marker.getPosition();
    //将map的中心点移动到点击的marker
    aMap.moveCamera(CameraUpdateFactory.
      changeLatLng(position));
  }

  private void showInfoWindowData(MakerInfoBean body) {
//        mMapInfoWindowAdapter.setLoadDataComplete(true);
//        mMapInfoWindowAdapter.setCurrentMarkerDetailData(body);
//        mCurrentClickMarker.showInfoWindow();
    mWindows = new MapInfoPopWindows(this);
    mWindows.show(body);
  }

  @Override
  public void onMyLocationChange(Location location) {
    if (isMoveMyLocation && !(location.getLatitude() == 0 && location.getLongitude() == 0)) {
      //移动中心点到我的位置，改变标记，后面无需再移动
      isMoveMyLocation = false;
      //移动到定位的地点
      aMap.moveCamera(CameraUpdateFactory.
        changeLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
    }
    else {
      //todo:需要检查这是否有bug，有时会一直显示定位失败
//            ToastUtil.showToastLong(getApplicationContext(), "定位失败");
    }
  }

  //地图点击事件
  @Override
  public void onMapClick(LatLng latLng) {
    hideMarkInfoWindow();
  }

  /**
   * 隐藏marker的信息窗口
   */
  private void hideMarkInfoWindow() {
    if (mWindows != null && mWindows.isShowing()) {
      mWindows.hide();
    }
  }

  private void tipGoneAnimation(View view) {
    ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
    alpha.setDuration(2500);
    alpha.addListener(new AnimatorListenerAdapter() {
      @Override
      public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        view.setVisibility(View.GONE);
      }
    });
    alpha.start();
  }
}
